﻿
using System;
using System.Collections.Generic;
using System.Text;
using LibUsbDotNet.Usb;
using LibUsbDotNet.Usb.Info;
using LibUsbDotNet.Usb.Internal;
using LibUsbDotNet.Usb.Main;
using LibUsbDotNet.DeviceNotify;
using LibUsbDotNet.DeviceNotify.Info;
using System.Windows.Forms;

namespace LIB_USB
{
	class Device
	{
		public UsbDevice dev;
		private UsbDeviceList devlist;
		//public UsbEndpointReader ep2in;
		//public UsbEndpointWriter ep2out;
		//public UsbEndpointReader ep1in;
		//public UsbEndpointWriter ep1out;
		//private UsbEndpointReader ep2in;
		//private UsbEndpointWriter ep2out;
		
		//打开设备
		public bool openDevice(int vid, int pid)
		{
			bool isopen = false;
			byte[] p = new byte[1];
			byte[] pp = new byte[4];
			devlist = UsbGlobals.DeviceList;
			foreach (UsbDevice dev in devlist)
			{
				if ((dev.Info.IdVendor == vid) && (dev.Info.IdProduct == pid))
				{
					if (dev.Open())
						if (dev.SetConfiguration(1) >= 0)
						if (dev.ClaimInterface(0) >= 0)
					{
						//ep2in = dev.OpenBulkEndpointReader(ReadEndpoints.Ep02);
						//ep2out = d12.OpenBulkEndpointWriter(WriteEndpoints.Ep02);
						//ep1in = d12.OpenInterruptEndpointReader(ReadEndpoints.Ep01);
						//ep1out = d12.OpenInterruptEndpointWriter(WriteEndpoints.Ep01);
						//d12.SetConfiguration(12);
						//d12.
						//ep2in = d12.OpenInterruptEndpointReader(ReadEndpoints.Ep02);
						//ep2out = d12.OpenInterruptEndpointWriter(WriteEndpoints.Ep02);
						//readbits();
						dev.IOControlMessage(0xC0, 1, 0, 0, new byte[0], 1000);
						dev.IOControlMessage(0xC0, 5, 0, 0, p, 1000);
						if (p[0] != 0)
						{
							MessageBox.Show("Ä¿±êÐ¾Æ¬Î´Á¬½Ó»òÊÇÊ±ÖÓÅäÖÃ´íÎó£¡");
						}
						dev.IOControlMessage(0xC0, 0x03, 0x30, 0, pp, 1000);
						MessageBox.Show(pp[3].ToString());
						
					}
					isopen = true;
				}
				else
				{
					isopen = false;
				}

			}
			return isopen;
		}
		
		//关闭设备
		public void closeDevice()
		{
			if (dev != null)
			{
				//ep2in.DataReceivedEnabled = false;
				//ep2in.Dispose();
				//ep2in.DataReceivedEnabled=false;
				//ep2in.Dispose();
				//ep2out.Dispose();
				//ep2out.Dispose();
				dev.ReleaseInterface(0);
				dev.SetConfiguration(0);
				dev.Close();
				dev = null;
			}
		}
		
		//读取数据
		public bool readbits()
		{
			dev.IOControlMessage(0x40, 4, 1, 0, new byte[0], 1000);
			return true;
		}
	}
}
